//获取应用实例
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
Page({
	data: {
    id:'',
    goodsMsg:[],
    swiperImgList:[
      ],
    imglist:[],
    hasImgList:false,
    skulist: [],
    commentList: [],
    commentStatistics:[],
    addressList:[],
    goods_id:'',
    is_collect:false,
    showModalStatus: false,//是否显示
    hasSku:false,
    gg_id: 0,//规格ID
    gg_txt: '',//规格文本
    gg_price: 0,//规格价格
    guigeList: [{ guige: '100', price: '150' }, { guige: '200', price: '150' }, { guige: '300', price: '150' }],
    num: 1,//初始数量
    hasYhq:false,
    /**
        * 页面配置
        */
    currentTab: 0,
  },


  getDeviceInfo: function () {
    let that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          deviceW: res.windowWidth,
          deviceH: res.windowHeight
        })
      }
    })
  },

  onReady(){
    this.getDeviceInfo();
  },
	onLoad: function(options) {
    var that=this;
    // console.log(options.id)
    that.setData({
      goods_id:options.id,
    })
    that.getGoodById(options.id);
  },

  onShow:function(){
    // console.log("onShow")
    var that=this;
    that.is_collect();
  },

  /**
      * 滑动切换tab
      */
  bindChange: function (e) {

    var that = this;
    that.setData({ currentTab: e.detail.current });

  },

  /**
   * 点击tab切换
   */
  swichNav: function (e) {

    var that = this;
    // console.log(e)

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },


  //获取商品详情
  getGoodById(id){
    wx.showLoading({
      title: '商品加载中',
      mask: false
    })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Tbk&a=getGoodsMsg',
      data:
      {
        num_iid:id,
        token:app.globalData.token
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if(res.data.code==0){
          that.setData({
            goodsMsg: res.data.data
          })
          if (res.data.data.coupon_amount>0){
            that.setData({
              hasYhq:true
            })
          }else{
            that.setData({
              hasYhq: false
            })
          }
          // var article = res.data.data.content_url;
          // WxParse.wxParse('article', '', article, that, 5);
          //   that.setData({
          //     goodsMsg: res.data.data.goodsMsg,
          //     goods_id: res.data.data.goodsMsg.goods_id,
          //     guigeList:res.data.data.skulist[0],
          //   })
          // }
          app.globalData.sku = that.data.skulist[0]
          // console.log(res.data.data.small_images.string)
          if (res.data.data.small_images.string.length > 0) {
            console.log("有商品相册")
            that.setData({
              hasImgList: true,
              swiperImgList: res.data.data.small_images.string
            })
            console.log(that.data.swiperImgList); 
            // that.getImgList();
          } else {
            console.log("没有商品相册")
            that.setData({
              hasImgList: false,
            })
          }
        }else {
          wx.showToast({
            title: ''+res.data.msg,
            icon:'none'
          })
          if(res.data.code==105){
            wx.reLaunch({
              url: '/pages/mine/phone-login',
            })
          }
        }
        
        // for (var i = 0; i < 1; i++) {
        //   var tempJson;
        //   res.data.data.goodsMsg.img = app.globalData.imgUrl + "" + res.data.data.goodsMsg.img;
        //   if(res.data.data.skulist.length>0){
        //     res.data.data.skulist[0].img = app.globalData.imgUrl + "" + res.data.data.skulist[0].img;
        //     tempJson = JSON.parse(res.data.data.skulist[0].sku)
        //     that.setData({
        //       skulist: tempJson,
        //       gg_txt: tempJson[0].value,
        //       hasSku:true,
        //     })
           
        //   }else{
        //     that.setData({
        //       hasSku: false,
        //     })
        //   }
        
        // that.getGoodsSku(res.data.data.num_iid);
        // that.getSubList(res.data.data.goodsMsg.cat_id);
        // that.getCommentStatistics();
        // that.getAddressList();
      }, fail: function () {

      }
    });
  },

  //获取商品属性配置
  getGoodsSku(goods_id) {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Goods&a=getGoodsSku',
      data:
      {
        goods_id: goods_id
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        // console.log(that.data.swiperImgList)
      }, fail: function () {

      }
    });
  },

  //获取商品相册
  getImgList() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/Goods/getImgList',
      data:
      {
        goods_id: that.data.goods_id  
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        // console.log(res);
        if(res.data.data.imglist.length>0){
          for(var i=0;i<res.data.data.imglist.length;i++){
            res.data.data.imglist[i].img = app.globalData.imgUrl + "" + res.data.data.imglist[i].img;
            that.setData({
              swiperImgList: res.data.data.imglist
            })
          }
        }
        // console.log(that.data.swiperImgList)
      }, fail: function () {

      }
    });
  },

  //获取商品评论统计
  getCommentStatistics() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/Goods/getCommentStatistics',
      data:
      {
        goods_id: that.data.goods_id
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        // console.log(res);
        if(res.data.code==1){
          that.setData({
            commentStatistics: res.data.data.statistics,
          })
          //判断是否有评论
          if (res.data.data.statistics.allnum>0){
            that.getComment();
          }
          // that.getComment();
        }
        wx.hideLoading();
      }, fail: function () {

      }
    });
  },
  //获取商品评论列表
  getComment() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/Goods/getComment',
      data:
      {
        goods_id: that.data.goods_id
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        var listLength=0;
        if(res.data.data.list.length>0){
          if (res.data.data.list.length >= 3) {
            listLength=3;
          }else{
            listLength = res.data.data.list.length;
          }
          // console.log(listLength);
          for (var i = 0; i < listLength; i++) {
            res.data.data.list[i].img = app.globalData.imgUrl + "" + res.data.data.list[i].img;
            res.data.data.list[i].user_avatar = app.globalData.imgUrl + "" + res.data.data.list[i].user_avatar;
            that.setData({
              commentList: res.data.data.list,
            })
          }
        }
        
      }, fail: function () {

      }
    });
  },

  //预览图片
  previewImage: function (e) {
    var imgUrl = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [imgUrl], //需要预览的图片http链接列表，注意是数组
      current: '', // 当前显示图片的http链接，默认是第一个
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  //获取推荐喜欢商品
  getSubList(id) {
    wx.showLoading({
      title: '商品加载中',
      mask: false
    })
    var that = this;
    // console.log(id)
    wx.request({
      url: app.globalData.api + '/index.php/wap/Goods/getList',
      data:
      {
        cat_id: id
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        // console.log(res);
        for (var i = 0; i < 1; i++) {
          res.data.data.list[0].img = app.globalData.imgUrl + "" + res.data.data.list[0].img;
        }
        that.setData({
          toplist:res.data.data.list
        })
        // for (var i = 0; i < 1; i++) {
        //   var tempJson;
        //   res.data.data.goodsMsg.img = app.globalData.imgUrl + "" + res.data.data.goodsMsg.img;
        //   if (res.data.data.skulist.length > 0) {
        //     res.data.data.skulist[0].img = app.globalData.imgUrl + "" + res.data.data.skulist[0].img;
        //     tempJson = JSON.parse(res.data.data.skulist[0].sku)
        //     that.setData({
        //       skulist: tempJson,
        //     })
        //   } else {
            
        //   }
        // }
      }, fail: function () {

      }
    });
  },

  toGoodDetail:function(e){
    console.log(e)
    wx.navigateTo({
      url: 'item?id='+e.currentTarget.id,
    })
  },

  //订单管理接口
  scanbuy(){
    if(app.globalData.token!=""){
      this.submitOrder();
    }else{
      wx.showToast({
        title: '请登录',
      })
      wx.reLaunch({
        url: '/pages/mine/login',
      })
    }
  },

  //查看图文详情
  toContent:function(e){
    console.log(e)
    wx.navigateTo({
      url: 'webview?url='+e.currentTarget.dataset.url,
    })
  },

  //获取收货地址列表
  getAddressList() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/ConsigneeAddress/getList',
      method: 'post',
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      data: {
        'token': '' + app.globalData.token
      },
      success: (res) => {
        // console.log(res)
        if (res.data.data.list.length > 0) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            if (res.data.data.list[i].is_default == 'Y') {
              that.setData({
                addressList: res.data.data.list[i],
                isDefaultAddress: true
              })
            }
          }
        } else {
          that.setData({
            isDefaultAddress: true
          })
        }
        // that.getGoodById(that.data.goods_id);
      },
    });
  },

  //立即购买
  submitOrder() {
    wx.navigateTo({
      url: 'order?goods_id='+this.data.goods_id,
    })
  },


  //用户是否收藏商品
  is_collect: function () {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=TbGoodsCollect&a=is_collect',
      data: {
        token: app.globalData.token,
        goods_id: that.data.goods_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success(res) {
        console.log(res)
        if(res.data.code==0){
          if(res.data.data.is_collect=='Y'){
            that.setData({
              is_collect: true
            })
          }else{
            that.setData({
              is_collect: false
            })
          }
        }
      }
    })
  },

  //收藏商品
  collect: function () {
    var that = this;
    if(app.globalData.token!=""){
      if (that.data.is_collect == true) {
        that.cancel();
      } else {
        that.saveCollect();
      }
    }else{
      wx.reLaunch({
        url: '/pages/mine/login',
      })
    }
  },

  saveCollect:function(){
    var that=this;
    wx.request({
      url: app.globalData.api + '/app.php?c=TbGoodsCollect&a=collect',
      data: {
        token: app.globalData.token,
        goods_id: that.data.goods_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          that.setData({
            is_collect:true
          })
          // wx.showToast({
          //   title: '' + res.data.msg,
          //   icon: 'success',
          //   duration: 1000
          // })
        }else{
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },

  //取消收藏
  cancel: function () {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=TbGoodsCollect&a=cancelCollect',
      data: {
        token: app.globalData.token,
        goods_id: that.data.goods_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          that.setData({
            is_collect: false
          })
          // wx.showToast({
          //   title: '' + res.data.msg,
          //   icon: 'success',
          //   duration: 1000
          // })
        }else{
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },

  // chooseType:function(){
  //   wx.navigateTo({
  //     url: 'commodity',
  //   })
  // },
  filter: function (e) {
    app.globalData.sku = this.data.skulist[e.currentTarget.dataset.index]
    // console.log(app.globalData.sku)
    var self = this, id = e.currentTarget.dataset.id, txt = e.currentTarget.dataset.txt, price = e.currentTarget.dataset.price
    self.setData({
      gg_id: id,
      gg_txt: txt,
      // gg_price: price
    });
  },

  /* 点击减号 */
  bindMinus: function () {
    var num = this.data.num;
    // 如果大于1时，才可以减  
    if (num > 1) {
      num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var num = this.data.num;
    // 不作过多考虑自增1  
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态  
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回  
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },


  //确定按钮
  cartModel:function(){
    this.hideModal();
    // this.submitOrder();
  },

  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  shopCart:function(){
    if(app.globalData.token!=''){
      wx.navigateTo({
        url: 'shop-cart',
      })
    }else{
      wx.reLaunch({
        url: 'login',
      })
    }
    
  },
  
  //加入购物车
  addCart() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Shopcart&a=add',
      data:
      {
        token:app.globalData.token,
        goods_id: that.data.goods_id,
        goods_num: that.data.num,
        // goods_sku:''
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        if(res.data.code==0){
          wx.showToast({
            title: '已加入购物车',
            icon:'success'
          })
        }else{
          wx.showToast({
            title: ''+res.data.msg,
            icon: 'none'
          })
        }
      }, fail: function () {

      }
    });
  },
});
